﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool
{

    private Dictionary<string, List<GameObject>> pool;//对象池
    private Dictionary<string, GameObject> prefabs;//预制体


    #region 单例
    private static ObjectPool _instance;

    private ObjectPool()
    {
        pool = new Dictionary<string, List<GameObject>>();
        prefabs = new Dictionary<string, GameObject>();
    }
    public static ObjectPool GetInstance()
    {
        if (_instance == null)
        {
            _instance = new ObjectPool();
        }
        return _instance;
    }
    #endregion

    #region 从对象池里获取对象
    public GameObject GetObj(string objName)
    {
        GameObject result = null;//结果对象
        if (pool.ContainsKey(objName))//判断是否有改名字的对象池
        {
            if (pool[objName].Count > 0)//对象池里有对象
            {
                result = pool[objName][0];//获取对象
                result.SetActive(true);//激活对象
                pool[objName].Remove(result);//从对象池中移除
                return result;//返回结果
            }
        }
        //如果没有改名字的对象池   或者改名字没有对象池
        GameObject prefab = null;
        if (prefabs.ContainsKey(objName))//已经加载过预制体
        {
            prefab = prefabs[objName];
        }
        else//    没有加载预制体
        {
            prefab = Resources.Load<GameObject>("Prefabs/" + objName);// 加载
            prefabs.Add(objName, prefab);                             //更新字典
        }

        result = UnityEngine.Object.Instantiate(prefab);//生成
        result.name = objName;//改名
        return result;//返回
    }
    #endregion

    #region 回收对象到对象池
    public void RecycleObj(GameObject obj)
    {
        obj.SetActive(false);
        if (pool.ContainsKey(obj.name))
        {
            pool[obj.name].Add(obj);
        }
        else
        {
            //创建池子
            pool.Add(obj.name, new List<GameObject>() { obj });
        }
    }

    #endregion



}
